// pages/register/register.js
import {
  register,
  signIn
} from '../../api/login'
Page({

  /**
   * Page initial data
   */
  data: {
    username: '',
    passowrd: '',
    repassword: '',
    allowRegister: false

  },
  userNameInput: function (e) {
    this.setData({
      username: e.detail.value
    })
    this.checkAllowRegister()
  },
  passwordInput: function (e) {
    this.setData({
      passowrd: e.detail.value
    })
    this.checkAllowRegister()
  },
  passwordInputConfirm: function (e) {
    this.setData({
      repassword: e.detail.value
    })
    this.checkAllowRegister()
  },
  checkAllowRegister: function () {
    const {
      username,
      passowrd,
      repassword
    } = this.data
    if (username.length > 0 && passowrd.length > 0 && repassword.length > 0) {
      this.setData({
        allowRegister: true
      })
    } else {
      this.setData({
        allowRegister: false
      })
    }
  },
  register() {
    const {
      username,
      passowrd,
      repassword
    } = this.data
    register(username, passowrd, repassword).then((res) => {
      if (res) {
        signIn(username, passowrd).then((res) => {
          console.log('resxxx', res)
          if (res) {
            let d = res.data
            wx.setStorageSync('"nickname"', d.nickname)
            wx.setStorageSync('"coinCount"', d.coinCount)
            wx.navigateBack({
              delta: 2,
            })
          }
        })
      }
    })
  },

  /**
   * Lifecycle function--Called when page load
   */
  onLoad: function (options) {

  },

  /**
   * Lifecycle function--Called when page is initially rendered
   */
  onReady: function () {

  },

  /**
   * Lifecycle function--Called when page show
   */
  onShow: function () {

  },

  /**
   * Lifecycle function--Called when page hide
   */
  onHide: function () {

  },

  /**
   * Lifecycle function--Called when page unload
   */
  onUnload: function () {

  },

  /**
   * Page event handler function--Called when user drop down
   */
  onPullDownRefresh: function () {

  },

  /**
   * Called when page reach bottom
   */
  onReachBottom: function () {

  },

  /**
   * Called when user click on the top right corner to share
   */
  onShareAppMessage: function () {

  }
})